package top.kwanghuee.api.predicates;

import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * @author: kwanghuee
 * @date: 2020/9/12 15:24
 */
@Component
public class AgeRoutePredicateFactory extends AbstractRoutePredicateFactory<AgeRoutePredicateFactory.Config> {
    /**
     * 构造函数
     */
    public AgeRoutePredicateFactory() {
        super(AgeRoutePredicateFactory.Config.class);
    }

    /**
     * 读取配置文件中的参数值，赋值到配置类的属性上
     * @return
     */
    @Override
    public List<String> shortcutFieldOrder() {
        // 顺序必须跟配置文件的值的顺序对应
        return Arrays.asList("minAge", "maxAge");
    }

    @Override
    public Predicate<ServerWebExchange> apply(AgeRoutePredicateFactory.Config config) {
        return new Predicate<ServerWebExchange>() {
            @Override
            public boolean test(ServerWebExchange serverWebExchange) {
                // 接收传入的age参数
                String ageStr = serverWebExchange.getRequest().getQueryParams().getFirst("age");
                // 先判断是否为空
                if (!StringUtils.isEmpty(ageStr)){
                    // 不为空再进行路由逻辑判断
                    int age = Integer.parseInt(ageStr);
                    if (age < config.getMaxAge() && age > config.getMinAge()){
                        return true;
                    }else {
                        return false;
                    }
                }
                return false;
            }
        };
    }

    /**
     * 配置类 用于接收配置文件中的对应参数
     */
    @Data
    @NoArgsConstructor
    public static class Config {
        private Integer minAge;
        private Integer maxAge;
    }
}
